﻿using System;
using System.Linq;
using Microsoft.Win32;

namespace InfoboardAdapterC.Common
{
    public class RegistryHelper
    {
        /// <summary>
        /// 读取指定名称的注册表的值
        /// </summary>
        /// <param name="subkey"></param>
        /// <param name="name"></param>
        /// <param name="root"></param>
        /// <returns></returns>
        public string GetRegistryData(RegistryKey root, string subkey, string name)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var registData = "";
            var myKey = root.OpenSubKey(subkey, true);
            if (myKey != null)
            {
                registData = myKey.GetValue(name).ToString();
            }

            return registData;
        }

        /// <summary>
        /// 向注册表中写数据
        /// </summary>
        /// <param name="subkey"></param>
        /// <param name="name"></param>
        /// <param name="root"></param>
        /// <param name="value"></param>
        public void SetRegistryData(RegistryKey root, string subkey, string name, string value)
        {
            var aimdir = root.CreateSubKey(subkey);
            aimdir?.SetValue(name, value);
        }

        /// <summary>
        /// 删除注册表中指定的注册表项
        /// </summary>
        /// <param name="subkey"></param>
        /// <param name="name"></param>
        /// <param name="root"></param>
        public void DeleteRegist(RegistryKey root, string subkey, string name)
        {
            var myKey = root.OpenSubKey(subkey, true);
            if (myKey == null) return;
            var subkeyNames = myKey.GetValueNames();
            foreach (var aimKey in subkeyNames)
            {
                if (aimKey == name)
                    myKey.DeleteValue(name);
            }
        }

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="subkey"></param>
        /// <param name="name"></param>
        /// <param name="root"></param>
        /// <returns></returns>
        public bool IsRegistryExist(RegistryKey root, string subkey, string name)
        {
            try
            {
                var myKey = root.OpenSubKey(subkey, false);
                if (myKey != null)
                {
                    if (myKey.GetValueNames().Any(aimKey => aimKey == name))
                    {
                        return true;
                    }
                }
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return false;
        } 
    }
}
